import React, { useRef } from 'react';
import { Form, Input, Button, Toast } from 'antd-mobile';
import { useNavigate, Link } from 'react-router-dom';
import SliderVerify from '../../components/SliderVerify';
import type { SliderVerifyRef } from '../../components/SliderVerify';
import './Login.css';

import axios from '../../axios'; // 新增

interface LoginFormValues {
  userName: string;
  passWord: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm<LoginFormValues>();
  const [isVerified, setIsVerified] = React.useState(false);
  const sliderRef = useRef<SliderVerifyRef>(null);

  const onFinish = async (values: LoginFormValues): Promise<void> => {
    if (!isVerified) {
      Toast.show({
        icon: 'fail',
        content: '请完成滑块验证',
      });
      return;
    }

    try {
      // 调试：打印表单数据
      console.log('登录请求参数:', values);
      // 调用后端登录接口
      const res = await axios.post('/bkc/login', values);
      // 存储用户id到本地
      if (res.data?.data?.id) {
        localStorage.setItem('userId', res.data.data.id);
      }
      Toast.show({
        icon: 'success',
        content: '登录成功！',
      });
      // 跳转首页
      
      navigate('/app/home');
    } catch (error: any) {
      // 调试：打印后端返回的完整错误
      console.error('登录失败:', error?.response);
      Toast.show({
        icon: 'fail',
        content: error?.response?.data?.message || '登录失败，请重试',
      });
    }
  };

  const handleVerify = (verified: boolean) => {
    setIsVerified(verified);
    if (verified) {
      Toast.show({
        icon: 'success',
        content: '验证成功',
      });
    } else {
      Toast.show({
        icon: 'fail',
        content: '验证失败，请重试',
      });
    }
  };

  return (
    <div className="login-container">
      <div className="login-header">
        <h2>欢迎登录</h2>
        <p>社区团购平台</p>
      </div>
      <Form
        form={form}
        onFinish={onFinish}
        layout='vertical'
        footer={
          <Button block type='submit' color='primary' size='large'>
            登录
          </Button>
        }
      >
        <Form.Item
          name="userName"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item
          name="passWord"
          label="密码"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input type='password' placeholder='请输入密码' />
        </Form.Item>
        <div className="slider-verification">
          <SliderVerify
            ref={sliderRef}
            width={310}
            height={155}
            onVerify={handleVerify}
            text="向右滑动完成验证"
            refreshIcon="↻"
            loadingIcon="⌛"
          />
        </div>
      </Form>
      <div className="login-footer">
        <Link to="/register">还没有账号？立即注册</Link>
        <br />
        <Button block color="primary" style={{marginTop: 8}} onClick={() => navigate('/face')}>
          人脸识别登录
        </Button>
      </div>
    </div>
  );
};

export default Login;

